#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#define SERVER_PORT 7878
int main()
{
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd == -1)
    {
        perror("err.");
        return -1;
    }
    printf("sockfd:%d\n",sockfd);
    //2.绑定IP+port
    int opt=1;
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    struct sockaddr_in saddr; //身份结构定义
    saddr.sin_family=AF_INET; //填充第一成员变量--协议族
    saddr.sin_port=htons(SERVER_PORT);//填充端口号 8888
    saddr.sin_addr.s_addr=inet_addr("192.168.1.54");//填充IP地址
    socklen_t addrlen=sizeof(saddr);
    if(bind(sockfd,(struct sockaddr *)&saddr,addrlen) == -1)
    {
        perror("err.");
        return -1;
    }
    printf("bind ok\n");
    //3.监听 将主动套接字变成被动套接字  
    listen(sockfd,6);
    printf("正在等待连接...\n");
    //4.accept,生成新的套接字--用于通信,当没有连接可建立的时候，阻塞
    int acceptfd= accept(sockfd,NULL,NULL);
    printf("连接已建立...\n");
    //5.发送
    char buf[1024]={0};
    float temp=0;
    float humi=0;
    while (1)
    {
        int ret=recv(acceptfd,buf,1024,0);
        if(ret == 0)
        {
            printf("client quit...\n");
            break;
        }
        else if(ret > 0)
        {
            printf("recv:%s\n",buf);
            sscanf(buf,"%f/%f",&temp,&humi);
            printf("temperature:%.2f, humidity:%.2f\n",temp,humi);
            if (temp > 27)
            {
                send(acceptfd,"FAN_ON",sizeof("FAN_ON"),0);
            }
            else if (temp < 27)
            {
                send(acceptfd,"FAN_OFF",sizeof("FAN_OFF"),0);
            }
            if (humi > 50)
            {
                send(acceptfd,"LD1_ON",sizeof("LD1_ON"),0);
            }
            else if (humi < 48)
            {
                send(acceptfd,"LD1_OFF",sizeof("LD1_OFF"),0);
            }
            memset(buf,0,1024);
        }
    }
    return 0;
}